/**
 * 通过群控软件，批量登录企业微信
 */
import { ExclamationCircleOutlined, SyncOutlined } from '@ant-design/icons'
import { truthy } from '@gnlab/utils'
import { Modal, Tag, Table, Result, Spin, Button, Checkbox } from 'antd'
import useBatchLogin, { ChooseAllStatus } from '@/desktop/logics/batch-login'
import type { Device } from '@/services/qywxs/batch-login'
import { Status } from '@/services/qywxs/batch-login'
import './batch.module.less'

type BatchLoginData = ReturnType<typeof useBatchLogin>
const { Idle, Queueing, LoggingIn, LoggedIn, Failed } = Status

export function BatchAddQywx(props: { visible: boolean; onClose: () => void }) {
  const { visible, onClose: rootRawOnClose } = props

  const rawOnClose = useCallback(
    (needConfirm: boolean) => {
      if (!needConfirm) return void rootRawOnClose()

      Modal.confirm({
        title: '确认结束自动寻机登录吗？',
        icon: <ExclamationCircleOutlined />,
        content: '还有没登录完成的设备',
        okText: '确定',
        cancelText: '取消',
        onOk: rootRawOnClose,
      })
    },
    [rootRawOnClose],
  )

  const batchLoginData = useBatchLogin(visible, rawOnClose)
  const { started, error, loadDevices, loading, devices, start, stop, onClose } = batchLoginData

  const hasError = truthy(error)
  const initialLoading = loading && !devices.length

  return <Modal
    open={visible}
    footer={null}
    width="870px"
    styleName="modal"
    destroyOnClose
    onCancel={onClose}
  >
    <div styleName="content">
      <header>
        {!started ? (
          <Button type="primary" onClick={start}>
            开始登录
          </Button>
        ) : (
          <Button type="primary" danger onClick={stop}>
            结束登录
          </Button>
        )}

        <Button type="link" disabled={loading} onClick={loadDevices}>
          刷新设备列表
        </Button>
      </header>

      <main>
        {hasError ? <Result styleName="error" status="warning" subTitle={error} /> : null}
        {!hasError && initialLoading ? (
          <Spin tip="正在载入设备列表..." styleName="loading" />
        ) : null}
        {!hasError && !initialLoading ? (
          <div styleName="devices">
            <DevicesTable {...batchLoginData} />
          </div>
        ) : null}
      </main>
    </div>
  </Modal>
}

function DevicesTable(props: BatchLoginData) {
  const {
    devices,
    chooseAble,
    chooseAllStatus,
    chooseAll,
    choose,
    compareId,
    compareName,
    compareStatus,
  } = props

  return <Table<Device> rowKey="id" dataSource={devices} scroll={{ y: 500 }} pagination={false}>
    <Table.Column<Device>
      key="choose"
      width={50}
      align="center"
      styleName="choose"
      title={
        <Checkbox
          checked={
            chooseAllStatus === ChooseAllStatus.Full || chooseAllStatus === ChooseAllStatus.Partial
          }
          disabled={chooseAllStatus === ChooseAllStatus.Disable}
          indeterminate={chooseAllStatus === ChooseAllStatus.Partial}
          onClick={chooseAll}
        />
      }
      render={(device: Device) => <Checkbox
        checked={device.status === Queueing}
        disabled={!chooseAble(device)}
        onClick={() => choose(device)}
      />}
    />

    <Table.Column<Device> title="No" key="no" width={55} render={(_, __, index) => index + 1} />

    <Table.Column<Device> title="设备ID" dataIndex="id" width={200} sorter={compareId} />

    <Table.Column<Device> title="设备名称" dataIndex="name" width={160} sorter={compareName} />

    <Table.Column<Device>
      title="状态"
      key="status"
      width={120}
      sorter={compareStatus}
      render={(device: Device) => <DeviceStatus device={device} {...props} />}
    />

    <Table.Column<Device>
      title="备注"
      key="info"
      render={(device: Device) => <DeviceExtraInfo device={device} {...props} />}
    />
  </Table>
}

function DeviceStatus(props: BatchLoginData & { device: Device }) {
  const { device, started } = props
  const { status } = device

  if (started && status === Queueing) return <Tag>等待中...</Tag>
  if (status === LoggingIn)
    return <Tag color="processing" icon={<SyncOutlined spin />}>
      登录中...
    </Tag>
  if (status === LoggedIn) return <Tag color="success">登录成功</Tag>
  if (status === Failed) return <Tag color="error">登录失败</Tag>
  return null
}

function DeviceExtraInfo(props: BatchLoginData & { device: Device }) {
  const { device, choose } = props
  const { status } = device

  if (status === Idle && device.hostname !== undefined)
    return <div styleName="hostname">[hostname] {device.hostname}（企微不在线）</div>

  if (status === LoggedIn) return <div styleName="hostname">[hostname] {device.hostname}</div>

  if (status === Failed) {
    return <div styleName="failed">
      <div styleName="failed-message">{device.error}</div>
      <a onClick={() => choose(device)}>重试</a>
    </div>
  }

  return null
}
